package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;

    @Autowired
    private UserAccountService userAccountService;

    /**
     * 根据充值订单编号查询充值信息
     *
     * @param orderNo
     * @return
     */
    @Override
    public RechargeInfo getRechargeInfo(String orderNo) {
        return rechargeInfoMapper.selectOne(
                new LambdaQueryWrapper<RechargeInfo>()
                        .eq(RechargeInfo::getOrderNo, orderNo)
        );
    }

    /**
     * 保存充值
     *
     * @param rechargeInfoVo
     * @return {orderNo:"充值订单编号"}
     */
    @Override
    public Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo) {
        RechargeInfo rechargeInfo = new RechargeInfo();
        rechargeInfo.setUserId(AuthContextHolder.getUserId());
        //生成充值订单编号
        String orderNo = "CZ" + DateUtil.today().replace("-", "") + IdUtil.getSnowflakeNextId();
        rechargeInfo.setOrderNo(orderNo);
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
        rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
        rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
        rechargeInfoMapper.insert(rechargeInfo);

        //TODO 超时未支付充值订单关闭，RabbitMQ延迟消息

        Map<String, String> map = new HashMap<>();
        map.put("orderNo", orderNo);
        return map;
    }

    /**
     * 微信支付成功后，处理充值业务
     *
     * @param orderNo
     * @return
     */
    @Override
    public void rechargePaySuccess(String orderNo) {
        //1.根据充值订单编号查询充值记录 判断状态是否为未支付
        RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(
                new LambdaQueryWrapper<RechargeInfo>()
                        .eq(RechargeInfo::getOrderNo, orderNo)
        );
        String rechargeStatus = rechargeInfo.getRechargeStatus();
        if (SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeStatus)) {
            //2.更新充值记录：已支付
            rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
            rechargeInfoMapper.updateById(rechargeInfo);
            //3.充值，对总金额、可用金额增加
            BigDecimal amount = rechargeInfo.getRechargeAmount();
            boolean flag = userAccountService.update(
                    null,
                    new LambdaUpdateWrapper<UserAccount>()
                            .setSql("total_amount = total_amount +" + amount)
                            .setSql("available_amount = available_amount +" + amount)
                            .setSql("total_income_amount = total_income_amount +" + amount)
                            .eq(UserAccount::getUserId, rechargeInfo.getUserId())
            );
            if (!flag) {
                throw new GuiguException(500, "充值失败！");
            }
            //4.新增账户变动日志
            userAccountService.saveUserAccountDetail(rechargeInfo.getUserId(), "充值", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, amount, orderNo);
        }
    }



}
